<template>
    <el-form :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px" ref="formRef">
        <el-form-item label="事项主题" prop="title">
            <el-input v-model="formData.title" placeholder="请填写事项主题" clearable maxlength="32"/>
        </el-form-item>
        <el-form-item label="事项描述" prop="content">
            <el-input v-model="formData.content" placeholder="请填写事项描述" type="textarea" :rows="3"/>
        </el-form-item>
        <el-form-item label="关联">
            <el-select v-model="selectedProjects" placeholder="请选择项目" clearable filterable multiple collapse-tags collapse-tags-tooltip>
                <el-option v-for="project in projectList" :key="project.id" :label="project.nickname" :value="project.id"/>
            </el-select>
            <el-select v-model="selectedMarkets" placeholder="请选择市场" clearable filterable multiple collapse-tags collapse-tags-tooltip style="margin: 0 10px">
                <el-option v-for="market in marketList" :key="market.id" :label="market.shortName" :value="market.id"/>
            </el-select>
            <el-select v-model="selectedStaffs" placeholder="请选择员工" clearable filterable multiple collapse-tags collapse-tags-tooltip>
                <el-option v-for="staff in staffList" :key="staff.id" :label="staff.name" :value="staff.id"/>
            </el-select>
        </el-form-item>
        <el-form-item label="付款日期">
            <el-date-picker v-model="formData.occurDate" type="date" placeholder="请选择日期" size="small" value-format="YYYY-MM-DD" @change="dateChange"/>
        </el-form-item>
        <el-form-item label="付款金额" prop="amount">
            <el-input-number v-model="formData.amount" :controls="false" :precision="2"/>
        </el-form-item>
        <el-form-item label="付款类别" prop="capitalTypeId">
            <el-select v-model="formData.capitalTypeId" placeholder="请选择付款类别" clearable filterable>
                <el-option v-for="item in capitalTypeList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
        </el-form-item>
        <el-form-item label="付款账户" prop="capitalAccountId">
            <el-select v-model="formData.capitalAccountId" placeholder="请选择账户" clearable filterable @change="accountChange">
                <el-option v-for="item in capitalAccounts" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            <span style="margin-left: 15px">账号：{{ selectedAccount ? selectedAccount.account : '-' }}</span>
        </el-form-item>
        <el-form-item label="附件">
            <Document :file-group="formData.type" v-model:resultList="attachList" :limit="9" code="MONEY"/>
        </el-form-item>
        <el-form-item label="备注">
            <el-input v-model="formData.remark" type="textarea" :rows="3" maxlength="500"/>
        </el-form-item>
        <el-form-item label="确认人" prop="executorIds">
            <el-select v-model="formData.executorIds" placeholder="请选择确认人" clearable filterable multiple collapse-tags collapse-tags-tooltip>
                <el-option v-for="item in confirmUsers" :key="item.userId" :label="item.userName" :value="item.userId"/>
            </el-select>
        </el-form-item>
        <el-form-item label="抄送人">
            <el-button type="primary" @click="openPicker" icon="ele-User">选择抄送人</el-button>
            <el-tag v-for="(user, i) in copyUsers" :key="user.id" style="margin-left: 10px" closable @close="removeUser(i)">{{ user.name }}</el-tag>
        </el-form-item>
        <el-row justify="end" v-if="!formData.id"> <!-- 日历/事项列表编辑处理 -->
            <el-button size="small" @click="closeForm">取消</el-button>
            <el-button size="default" type="primary" v-if="!formData.id && !formData.agendaMatterId" @click="submitData(formRef)">保存</el-button>
            <el-button size="default" type="primary" v-else-if="formData.state == 0 || formData.state == 1" @click="matterConfirm">确认</el-button>
        </el-row>

        <org-picker ref="orgPicker" title="请选择抄送人" multiple type="user" :selected="copyUsers" @ok="confirmPick"/>
    </el-form>
</template>

<script>
// 其他付款

import {reactive, toRefs, ref, onMounted} from 'vue'
import capitalTypeApi from '/@/api/money/capitalType'
import capitalAccountApi from '/@/api/money/capitalAccount'
import relateItemApi from '/@/api/matter/relateItem'
import moneyApi from '/@/api/money'
import Cookies from 'js-cookie'
import Document from '/@/components/document/index.vue'
import {formatDate} from '/@/utils/formatTime'
import OrgPicker from '/@/views/setting/workflow/process/OrgPicker.vue'
import moneyMatterApi from '/@/api/matter/money'
import {ElMessage} from 'element-plus'
import commonApi from '/@/api/commonApi'
import {getRelatableMap} from '/@/api/matter'

export default {
    name: 'OtherPay',
    emits: ['update:code'],
    props: {
        code: {
            default: null,
            type: String
        },
        relatableMap: {
            type: Object,
            default: null
        }
    },
    components: {
        Document,
        OrgPicker
    },
    setup(props, context) {
        const {relatableMap} = toRefs(props)
        const formRef = ref()
        const orgPicker = ref()
        const state = reactive({
            formData: {
                id: null,
                title: '其他付款',
                content: '',
                occurDate: null,
                actionStartTime: null,
                actionEndTime: null,
                executorIds: [],    // 只会在资金流水发起, 默认发起人就是确认人
                copyIds: [],
                relateItems: [],
                remark: null,
                attach: '',
                attachNames: '',
                priority: 0,
                remindState: 'NONE',
                remindType: [],
                amount: 0,
                capitalStreamNo: null,    // 钱相关事项特有流水号, 系统自动生成
                capitalTypeId: null,
                capitalAccountId: null,
                type: 'OTHER_PAY'
            },
            formRules: {
                title: {required: true, message: '请填写事项主题', trigger: 'blur'},
                amount: {required: true, message: '请填写付款金额', trigger: 'blur'},
                capitalTypeId: {required: true, message: '请选择付款类别', trigger: 'change'},
                capitalAccountId: {required: true, message: '请选择付款账户', trigger: 'change'},
                executorIds: {required: true, message: '请选择确认人', trigger: 'change'}
            },
            relatableItem: null,    // 可关联项
            copyUsers: [],      // 选中的抄送人
            confirmUsers: [],   // 确认人列表
            projectList: [],  // 项目列表
            marketList: [],   // 市场列表
            staffList: [],    // 员工列表
            selectedProjects: [],   // 选中的项目
            selectedMarkets: [],    // 选中的市场
            selectedStaffs: [],   // 选中的员工
            attachList: [],   // 附件列表
            capitalTypeList: [],  // 支出类别列表
            capitalAccounts: [],    // 资金流水账户列表
            selectedAccount: null    // 选中的资金流水账户
        })

        const dateChange = (val) => {
            if (val) {
                state.formData.actionEndTime = state.formData.actionStartTime = val + state.formData.actionStartTime.substring(10)
            }
        }
        const accountChange = (accountId) => {
            if (accountId) {
                for (let i = 0; i < state.capitalAccounts.length; i++) {
                    let account = state.capitalAccounts[i]
                    if (accountId == account.id) {
                        state.selectedAccount = account
                        break
                    }
                }
            } else {
                state.selectedAccount = null
            }
        }
        // 初始化确认人数据列表
        const initConfirmUser = () => {
            // 获取确认人列表（钱模块）
            moneyApi.getCapitalUsers('capitalStream').then(res => {
                state.confirmUsers = res.data
                // 获取确认人的历史选择记录
                moneyApi.getConfirmRecord(state.formData.type).then(res => {
                    if (res.data) {
                        state.formData.executorIds = []
                        res.data.forEach(confirmId => {
                            for (let i = 0; i < state.confirmUsers.length; i++) {
                                let confirmUser = state.confirmUsers[i]
                                if (confirmUser.userId == confirmId) {
                                    state.formData.executorIds.push(confirmId)
                                    break
                                }
                            }
                        })
                    } else {  // 没有历史选择记录
                        // 如果当前用户为确认人之一, 默认加入
                        let selfId = Cookies.get('userId')
                        for (let i = 0; i < state.confirmUsers.length; i++) {
                            let confirmUser = state.confirmUsers[i]
                            if (confirmUser.userId == selfId) {
                                state.formData.executorIds = [state.selfId]
                                break
                            }
                        }
                    }
                }).catch(e => console.log(e))
            }).catch(e => console.log(e))
        }
        const openPicker = () => {
            orgPicker.value.show()
        }
        // 抄送人确认选择回调
        const confirmPick = (users) => {
            if (users && users.length > 0) {
                state.copyUsers = users
                state.formData.copyIds = []
                users.forEach(user => state.formData.copyIds.push(user.id))
            } else {
                state.copyUsers = state.formData.copyIds = []
            }
        }
        // 抄送人标签移除方法
        const removeUser = (index) => {
            state.copyUsers.splice(index, 1)
            state.formData.copyIds.splice(index, 1)
        }
        const submitData = (formEl) => {
            formEl.validate(async (valid) => {
                if (!valid) {
                    return false
                }

                let params = JSON.parse(JSON.stringify(state.formData))
                // 列表转逗号分割字符串提交
                if (state.attachList.length > 0) {  // 组装附件地址和名称
                    for (let i = 0; i < state.attachList.length; i++) {
                        let item = state.attachList[i]
                        params.attach += item.src
                        params.attachNames += item.name
                        if (i < state.attachList.length - 1) {
                            params.attach += ','
                            params.attachNames += '，'
                        }
                    }
                }
                params.relateItems = []
                if (state.selectedProjects.length > 0) {
                    let relatable = state.relatableItem['Project']
                    state.selectedProjects.forEach(project => params.relateItems.push({
                        code: relatable.code,
                        agendaMatterRelatableId: relatable.id,
                        seRelateDataId: project['id'],
                        label: relatable.label + '/' + project['nickname']
                    }))
                }
                if (state.selectedMarkets.length > 0) {
                    let relatable = state.relatableItem['Market']
                    state.selectedMarkets.forEach(market => params.relateItems.push({
                        code: relatable.code,
                        agendaMatterRelatableId: relatable.id,
                        seRelateDataId: market['id'],
                        label: relatable.label + '/' + market['shortName']
                    }))
                }
                if (state.selectedStaffs.length > 0) {
                    let relatable = state.relatableItem['Staff']
                    state.selectedStaffs.forEach(staff => params.relateItems.push({
                        code: relatable.code,
                        agendaMatterRelatableId: relatable.id,
                        seRelateDataId: staff['id'],
                        label: relatable.label + '/' + staff['name']
                    }))
                }
                moneyMatterApi.submitMatter(params).then(res => {
                    if (res.data) {
                        // 提交事项后, 提交附件
                        commonApi.fileRelevanceModule(state.attachList)
                        ElMessage.success('提交成功！')
                        closeForm()
                    }
                }).catch(e => console.log(e))
            }).catch(e => console.log(e))
        }
        const matterConfirm = () => {
            moneyMatterApi.moneyConfirm(state.formData).then(res => {
                if (res.data) {
                    ElMessage.success('确认成功！')
                    closeForm()
                }
            }).catch(e => console.log(e))
        }
        const initData = () => {
            state.formData = {
                id: null,
                title: '其他付款',
                content: '',
                occurDate: null,
                actionStartTime: null,
                actionEndTime: null,
                executorIds: [],    // 只会在资金流水发起, 默认发起人就是确认人
                relateItems: [],
                remark: null,
                attach: '',
                attachNames: '',
                priority: 0,
                remindState: 'NONE',
                remindType: [],
                amount: 0,
                capitalStreamNo: null,    // 钱相关事项特有流水号, 系统自动生成
                capitalTypeId: null,
                capitalAccountId: null,
                type: 'OTHER_PAY'
            }
            // 收支类别数据
            capitalTypeApi.getList(1).then(res => state.capitalTypeList = res.data).catch(e => console.log(e))
            // 资金流水帐户
            capitalAccountApi.getList().then(res => state.capitalAccounts = res.data).catch(e => console.log(e))
            // 项目、市场、员工数据
            relateItemApi.getProjectList().then(res => state.projectList = res.data).catch(e => console.log(e))
            relateItemApi.getMarketList().then(res => state.marketList = res.data).catch(e => console.log(e))
            relateItemApi.getStaffList().then(res => state.staffList = res.data).catch(e => console.log(e))
        }
        const closeForm = () => context.emit('update:code', '')

        onMounted(() => {
            if (relatableMap.value == null) {
                getRelatableMap().then(res => state.relatableItem = res.data).catch(e => console.log(e))
            } else {
                state.relatableItem = JSON.parse(JSON.parse(relatableMap.value))
            }
            initData()
            initConfirmUser()
            // 行动时间默认现在
            let nowTime = formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS')
            state.formData.actionStartTime = state.formData.actionEndTime = nowTime
            state.formData.occurDate = nowTime.substring(0, 10)
        })

        return {
            formRef,
            orgPicker,
            ...toRefs(state),
            closeForm,
            submitData,
            dateChange,
            accountChange,
            openPicker,
            confirmPick,
            removeUser,
            matterConfirm
        }
    }
}
</script>

<style scoped lang="scss">

</style>
